package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.PageResult;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.entity.VolunteerCertificate;
import com.tju.ocean_ecology_website.entity.VolunteerInfo;
import com.tju.ocean_ecology_website.service.UserService;
import com.tju.ocean_ecology_website.service.VolunteerCertificateService;
import com.tju.ocean_ecology_website.service.VolunteerInfoService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 志愿者证书控制器
 */
@RestController
@RequestMapping("/api/volunteer")
public class VolunteerCertificateController {

    @Resource
    private UserService userService;

    @Resource
    private VolunteerInfoService volunteerInfoService;

    @Resource
    private VolunteerCertificateService volunteerCertificateService;

    /**
     * 获取志愿者证书
     *
     * @return 证书列表
     */
    @GetMapping("/certificate")
    public ResponseEntity<ApiResponse<PageResult<VolunteerCertificate>>> getVolunteerCertificate(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        // 查询志愿者证书
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Page<VolunteerCertificate> certificatePage = volunteerCertificateService.queryByPage(null, pageRequest);

        // 创建分页结果
        PageResult<VolunteerCertificate> pageResult = PageResult.fromPage(certificatePage, page);

        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 下载证书
     *
     * @param id 证书ID
     * @return 证书PDF文件
     */
    @GetMapping("/certificate/{id}/download")
    public ResponseEntity<byte[]> downloadCertificate(@PathVariable("id") Long id) {
        // 查询证书信息
        VolunteerCertificate certificate = volunteerCertificateService.queryById(id);
        if (certificate == null) {
            return ResponseEntity.badRequest().body(null);
        }

        // 生成证书PDF
        byte[] pdfBytes = volunteerCertificateService.generateCertificatePdf(id);
        if (pdfBytes.length == 0) {
            return ResponseEntity.badRequest().body(null);
        }

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", certificate.getCertificateName() + ".pdf");

        return ResponseEntity.ok()
                .headers(headers)
                .body(pdfBytes);
    }


}
